//
//  SETagsCollectionView.swift
//  SmartEyeForDoctor
//
//  Created by QDSG on 2021/6/10.
//

import UIKit

class SETagsCollectionView: UICollectionView {
    
    var titles: [String] = [] { didSet { reloadData() } }

    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: layout)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupUI()
    }
    
    private func setupUI() {
        isUserInteractionEnabled = false
        contentInsetAdjustmentBehavior = .never
        backgroundColor = .clear
        delegate = self
        dataSource = self
        register(SETagsCollectionViewCell.nibForCell(),
                                forCellWithReuseIdentifier: SETagsCollectionViewCell.reuseIdentifier())
    }
}

// MARK: - UICollectionViewDataSource

extension SETagsCollectionView: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return titles.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: SETagsCollectionViewCell.reuseIdentifier(), for: indexPath) as! SETagsCollectionViewCell
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        (cell as! SETagsCollectionViewCell).title = titles[indexPath.item]
    }
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
}

// MARK: - UICollectionViewDelegateFlowLayout

extension SETagsCollectionView: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let title = titles[indexPath.item]
        let width = title.width(height: 20, font: .regular(12))
        return CGSize(width: width + 5 * 2, height: 20)
    }
}
